<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="搜索帖子标题"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.categoryId"
        placeholder="选择分类"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in categoryOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-model="listQuery.sort"
        placeholder="排序方式"
        style="width: 120px"
        class="filter-item"
      >
        <el-option label="最新" value="new" />
        <el-option label="热门" value="hot" />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="danger"
        icon="el-icon-delete"
        @click="handleDeleteMultiple"
        :disabled="multipleSelection.length === 0"
      >
        批量删除
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column width="200px" align="center" label="标题">
        <template slot-scope="scope">
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>

      <el-table-column width="120px" align="center" label="作者">
        <template slot-scope="scope">
          <span>{{ scope.row.nickname }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100px" align="center" label="分类">
        <template slot-scope="scope">
          <el-tag>{{ getCategoryName(scope.row.categoryId) }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column width="80px" align="center" label="精华">
        <template slot-scope="scope">
          <el-tag :type="scope.row.featured ? 'success' : 'info'">
            {{ scope.row.isFeatured ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column width="80px" align="center" label="浏览">
        <template slot-scope="scope">
          <span>{{ scope.row.viewCount }}</span>
        </template>
      </el-table-column>

      <el-table-column width="80px" align="center" label="点赞">
        <template slot-scope="scope">
          <span>{{ scope.row.likeCount }}</span>
        </template>
      </el-table-column>

      <el-table-column width="80px" align="center" label="评论">
        <template slot-scope="scope">
          <span>{{ scope.row.commentCount }}</span>
        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" label="发布时间">
        <template slot-scope="scope">
          <span>{{ new Date(scope.row.createTime).getTime() | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="280">
        <template slot-scope="scope">
          <el-button
            size="mini"
            :type="scope.row.isFeatured ? 'warning' : 'success'"
            @click="handleToggleFeatured(scope.row)"
          >
            {{ scope.row.isFeatured ? '取消精华' : '设为精华' }}
          </el-button>
          <el-button
            size="mini"
            type="primary"
            @click="handleViewComments(scope.row)"
          >
            查看评论
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { getPosts, deletePost, setFeaturedPost } from '@/api/post'
import { getCategories } from '@/api/category'
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import { parseTime } from '@/utils'

export default {
  name: 'PostList',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        categoryId: undefined,
        sort: 'new'
      },
      categoryOptions: [],
      multipleSelection: []
    }
  },
  created() {
    this.getList()
    this.getCategories()
  },
  methods: {
    async getList() {
      this.listLoading = true
      try {
        const response = await getPosts(this.listQuery)
        this.list = response.data.records
        this.total = response.data.total
      } catch (error) {
        console.error('获取帖子列表失败:', error)
      } finally {
        this.listLoading = false
      }
    },
    async getCategories() {
      try {
        const response = await getCategories()
        this.categoryOptions = response.data
      } catch (error) {
        console.error('获取分类列表失败:', error)
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getCategoryName(categoryId) {
      const category = this.categoryOptions.find(item => item.id === categoryId)
      return category ? category.name : '未知'
    },
    handleViewComments(row) {
      this.$router.push(`/forum/comments/${row.id}`)
    },
    handleDelete(row) {
      this.$confirm('确定要删除这个帖子吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deletePost(row.id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        } catch (error) {
          console.error('删除帖子失败:', error)
        }
      })
    },
    handleDeleteMultiple() {
      if (this.multipleSelection.length === 0) {
        return
      }
      
      this.$confirm(`确定要删除选中的 ${this.multipleSelection.length} 个帖子吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const deletePromises = this.multipleSelection.map(item => deletePost(item.id))
          await Promise.all(deletePromises)
          this.$message({
            type: 'success',
            message: '批量删除成功!'
          })
          this.multipleSelection = []
          this.getList()
        } catch (error) {
          console.error('批量删除帖子失败:', error)
        }
      })
    },
    
    async handleToggleFeatured(row) {
      const action = row.featured ? '取消精华' : '设为精华'
      const confirmMessage = `确定要${action}这个帖子吗？`
      
      try {
        await this.$confirm(confirmMessage, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await setFeaturedPost(row.id, row.featured ? 0 : 1)
        
        this.$message({
          type: 'success',
          message: `${action}成功!`
        })
        
        // 更新当前行的精华状态
        row.featured = !row.featured
      } catch (error) {
        if (error !== 'cancel') {
          console.error(`${action}帖子失败:`, error)
          this.$message({
            type: 'error',
            message: `${action}失败，请重试`
          })
        }
      }
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.filter-item {
  margin-right: 10px;
}
</style>